<template>
  <div class="container">
    <div class="mainContainer">
      <el-col class="departmentMenu tree">
        <div class="titleBox">
          <!-- <div class="operation" style="float: right;" @click="handleAdd">添加菜单</div> -->
          <el-button
            class="commonBut saveBtn funComBut"
            style="float: right"
            icon="icon iconfont icontianjia"
            @click="handleAdd"
            v-show="isShowAdd"
          >
            <span class="opetareText">添加菜单</span>
          </el-button>
          <div class="title">菜单列表【排序值】</div>
        </div>
        <el-tree
          :data="menuData"
          empty-text="尚未创建菜单"
          node-key="index"
          :props="defaultProps"
          default-expand-all
          @node-click="handleNodeClick"
          ref="tree"
          :default-checked-keys="[0]"
          :render-content="renderContent"
          style="background: #e7ecf3; padding: 15px"
        ></el-tree>
      </el-col>
      <el-col class="departmentModify" v-if="selectId !== -1">
        <div class="titleBox">
          <!-- <el-button class="commonBut saveBtn funComBut"  style="float: right;" @click="handleDelete">删除菜单</el-button>
            <el-button class="commonBut saveBtn funComBut"  style="float: right;" @click="handleDelete">修改菜单</el-button> -->
          <el-button
            class="commonBut saveBtn funComBut"
            style="float: right"
            @click="handleDelete"
            v-if="action === 'show' && isShowDel"
            >删除菜单</el-button
          >
          <el-button
            class="commonBut saveBtn funComBut"
            style="float: right; margin-right: 20px"
            @click="handleModify"
            v-if="action === 'show' && isShowUpdate"
            >修改菜单</el-button
          >
          <div class="title">{{ showTitle }}</div>
        </div>
        <el-form
          :model="formData"
          :rules="action === 'show' ? null : formRules"
          ref="formData"
          label-width="120px"
          class="form"
          v-if="showFrom"
        >
          <el-form-item
            :label="'父级菜单'.concat(action === 'show' ? '：' : '')"
            style="width: 100%"
            prop="inventedId"
          >
            <div v-show="action === 'show'">{{ selectText }}</div>
            <el-cascader
              :options="menuOptions"
              :props="CascaderProps"
              v-model="formData.inventedId"
              ref="menuOptionsBox"
              @change="handleChange"
              v-show="action !== 'show'"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item
            prop="name"
            :label="'菜单名称'.concat(action === 'show' ? '：' : '')"
          >
            <div v-if="action === 'show'">
              {{ formatTd(0, 0, formData.name) }}
            </div>
            <el-input
              v-model.trim="formData.name"
              placeholder="请输入菜单名称"
              class="input"
              clearable
              v-else
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="code"
            :label="'菜单编码'.concat(action === 'show' ? '：' : '')"
          >
            <div v-if="action === 'show'">
              {{ formatTd(0, 0, formData.code) }}
            </div>
            <el-input
              :disabled="action == 'modify'"
              v-model.trim="formData.code"
              placeholder="请输入菜单编码"
              class="input"
              clearable
              v-else
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="url"
            :label="'菜单地址'.concat(action === 'show' ? '：' : '')"
          >
            <div
              class="ellipsis"
              v-if="action === 'show'"
              :title="formatTd(0, 0, formData.url)"
            >
              {{ formatTd(0, 0, formData.url) }}
            </div>
            <el-input
              v-model.trim="formData.url"
              placeholder="请输入菜单地址"
              class="input"
              clearable
              v-else
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="icon"
            :label="'菜单图标'.concat(action === 'show' ? '：' : '')"
          >
            <span
              v-show="!formData.icon && action !== 'show'"
              @click="isShowIcon = true"
              style="cursor: pointer"
              >请点击选择菜单图标</span
            >
            <i
              :class="formData.icon"
              v-show="formData.icon"
              @click="toShowIcon"
              style="cursor: pointer"
            ></i>
            <!-- <i :class="formData.icon" v-if="formData.icon" @click="isShowIcon = 'true' && action!=='show'" style="cursor: pointer;"></i> -->
            <span v-show="!formData.icon && action === 'show'">--</span>
            <div class="iconList" v-show="isShowIcon">
              <iconList @getData="getData"></iconList>
            </div>
          </el-form-item>
          <el-form-item
            prop="sortCode"
            :label="'排序值'.concat(action === 'show' ? '：' : '')"
            style="width: 100%"
          >
            <div v-if="action === 'show'">
              {{ formatTd(0, 0, formData.sortCode) }}
            </div>
            <el-input-number
              v-model="formData.sortCode"
              v-if="action !== 'show'"
              :min="0"
              :max="10000000000000000"
              placeholder="请输入菜单排序"
            >
            </el-input-number>
            <span v-if="action !== 'show'">（排序值越大越靠前）</span>
          </el-form-item>
          <el-form-item label="用户属性">
            <el-checkbox
              label="管理员不可见"
              v-model="managerIsShow"
              v-bind="{ disabled: action === 'show' }"
            ></el-checkbox>
          </el-form-item>
          <el-form-item
            prop="url"
            :label="'备注'.concat(action === 'show' ? '：' : '')"
          >
            <div v-if="action === 'show'">
              {{ formatTd(0, 0, formData.remark) }}
            </div>
            <el-input
              v-model.trim="formData.remark"
              placeholder="请输入备注"
              class="input"
              clearable
              v-else
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="url"
            :label="'打开方式'.concat(action === 'show' ? '：' : '')"
          >
            <!-- <div v-if="action==='show'">{{ formatTd(0,0,formData.menuSource) }}</div> -->
            <el-radio-group
              v-model="formData.menuSource"
              :max="1"
              :disabled="action === 'show'"
            >
              <el-radio label="SYSTEM" key="1">当前窗口</el-radio>
              <el-radio label="EXTERNAL" key="2">新开窗口</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="action !== 'show'" style="width: 100%">
            <el-button
              class="commonBut saveBtn"
              @click="handleSave"
              :loading="isSaveLoading"
              >保存</el-button
            >
            <el-button
              class="commonBut"
              @click="cancelSave"
              v-if="action === 'modify'"
              >取消</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <div class="emptyBox" v-else>
        <div class="departmentModify empty" v-if="formData.id != '0'">
          请先选择菜单，再进行操作
        </div>
        <div class="departmentModify empty" v-else>
          一级菜单为【应用模块】，不可在此处修改
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import iconList from '@/components/publicCom/iconList'

export default {
  name: 'menuModule',
  components: {
    iconList,
  },
  data() {
    var checkIcon = (rule, value, callback) => {
      this.$nextTick(function () {
        if (!this.formData.icon) {
          return callback(new Error('请选择菜单图标'))
        } else {
          callback()
        }
      })
    }
    return {
      // 树结构
      menuData: [],
      defaultProps: {
        children: 'child',
        // label: 'name',
        value: 'inventedId',
        checkStrictly: true,
      },
      CascaderProps: {
        children: 'child',
        label: 'name',
        value: 'inventedId',
        checkStrictly: true,
      },
      selectId: -1, //无任何菜单
      isSaveLoading: false,
      action: 'show',
      formData: {
        id: '',
        appId: '',
        parentId: '',
        name: '',
        code: '',
        url: '',
        icon: '',
        sortCode: '',
        oldParentId: '',
        inventedId: '',
        isShow: '',
        remark: '',
        menuSource: 'SYSTEM',
      },
      inventedId: '',
      selectText: '',
      formRules: {
        inventedId: {
          required: true,
          message: '请输入父级菜单',
          trigger: 'blur',
        },
        name: {
          required: true,
          message: '请输入菜单名称',
          trigger: 'blur',
        },
        code: {
          required: true,
          message: '请输入菜单编码',
          trigger: 'blur',
        },
        icon: {
          required: true,
          // message: "请输入菜单图标",
          validator: checkIcon,
          trigger: 'blur',
        },
        sortCode: {
          required: true,
          pattern: /(^[1-9]\d*$)/,
          message: '请输入正整数',
          trigger: 'blur',
        },
      },
      loading: true,
      isShow: false,
      tableList: [],
      // requestUrl: "api-a/cs/alert/expand/monitor/listbypage",
      filterField: {
        name: '',
      },
      multipleSelection: [],
      //
      menuOptions: '',
      isShowIcon: '',
      showTitle: '',
      showFrom: false,
      isShowDel: '',
      isShowUpdate: '',
      isShowAdd: '',
      managerIsShow: false,
    }
  },
  created() {
    this.getDept()
    this.getMenuOptions()
    this.isShowAdd = this.$store.state.buttonLimitsArr.indexOf('menu:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('menu:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('menu:delete') > -1
  },
  updated() {
    if (
      $('.departmentModify')[0].clientHeight >
      $('.mainContainer')[0].clientHeight
    ) {
      $('.departmentMenu')[0].style.height =
        $('.departmentModify')[0].clientHeight + 'px'
    }
  },
  methods: {
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>
            {data.name} [{data.sortCode || '-'}]
          </span>
        </span>
      )
    },
    handleChange(value) {
      this.formData.parentId =
        this.$refs.menuOptionsBox.getCheckedNodes()[0].data.id
      this.formData.appId =
        this.$refs.menuOptionsBox.getCheckedNodes()[0].data.appId
      this.selectText = this.$refs.menuOptionsBox
        .getCheckedNodes()[0]
        .pathLabels.join('>')
    },
    updateDept() {
      this.axios({
        method: 'put',
        url: this.api.updateDeptApi,
      })
        .then((resp) => {
          //   this.stateOptions = resp.data;
        })
        .catch((resp) => {})
    },
    deleteDept() {
      this.axios({
        method: 'delete',
        url: this.api.updateDeptApi,
      })
        .then((resp) => {
          //   this.stateOptions = resp.data;
        })
        .catch((resp) => {})
    },
    //开启loading
    openFullScreen() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      return loading
    },
    closeFullScreen(loading) {
      loading.close()
    },
    getDept() {
      this.openFullScreen()
      this.axios({
        method: 'post',
        url: '/api-m/menus/tree',
      })
        .then((resp) => {
          this.menuData = resp.data.result
          this.closeFullScreen(this.openFullScreen())
          //   this.stateOptions = resp.data;
        })
        .catch((resp) => {
          this.closeFullScreen(this.openFullScreen())
        })
    },
    getMenuOptions() {
      this.axios({
        method: 'post',
        url: '/api-m/menus/combobox',
      })
        .then((resp) => {
          this.menuOptions = resp.data.result
          //   this.stateOptions = resp.data;
        })
        .catch((resp) => {})
    },
    getData(data) {
      this.formData.icon = data
      this.isShowIcon = false
    },
    handleNodeClick(item) {
      this.formData.id = item.id
      if (item.id == '0') {
        this.selectId = -1
        return
      }

      this.selectId = 0
      // this.appId = item.id;
      // this.$refs['formData'].resetFields();
      this.getMenuInfo(item.id)
    },
    getMenuInfo(id) {
      this.axios({
        method: 'post',
        url: '/api-m/menus/detail',
        data: {
          id: id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              var data = response.data.result

              this.formData.appId = data.appId
              this.formData.parentId = data.parentId
              this.formData.name = data.name
              this.formData.code = data.code
              this.formData.url = data.url
              this.formData.icon = data.icon
              this.formData.sortCode = data.sortCode
              this.formData.oldParentId = data.oldParentId
              this.formData.inventedId = data.inventedId
              this.formData.remark = data.remark
              this.formData.menuSource = data.menuSource
              this.managerIsShow = data.isShow === 0 ? true : false

              this.action = 'show'
              var that = this
              setTimeout(function () {
                that.selectText = that.$refs.menuOptionsBox
                  .getCheckedNodes()[0]
                  .pathLabels.join('>')
              }, 100)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            // this.canLogin = false;
          }
        )
        .catch((error) => {
          this.canLogin = false
        })
    },
    handleAdd() {
      this.action = 'add'

      if (this.menuData.length !== 0) {
        this.selectId = 0
      }
      this.formData.appId = ''
      this.formData.parentId = ''
      this.formData.name = ''
      this.formData.code = ''
      this.formData.url = ''
      this.formData.icon = ''
      this.formData.sortCode = ''
      this.formData.oldParentId = ''
      this.formData.id = ''
      this.formData.inventedId = ''
      this.formData.remark = ''
      this.getMenuOptions()
      // this.$refs['formData'].resetFields();
    },

    handleDelete(index, row) {
      this.$confirm(
        '确认删除菜单【' + this.formData.name + '】？',
        '删除菜单',
        {
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning',
        }
      )
        .then(() => {
          this.toDel()
        })
        .catch(() => {})
    },
    toDel() {
      this.axios({
        method: 'post',
        url: '/api-m/menus/delete',
        data: {
          id: this.formData.id,
        },
      })
        .then(
          (response) => {
            this.canLogin = false
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$nextTick(() => {
                this.getDept()
                this.selectId = -1
                // this.action = "show";
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.canLogin = false
          }
        )
        .catch((error) => {
          this.canLogin = false
        })
    },
    handleModify() {
      this.action = 'modify'
      this.getMenuOptions()
      // this.$refs['formData'].resetFields();
    },
    handleSave() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // if (this.action === "add") {
          // var that = this;
          // this.$nextTick(() => {
          //   that.$refs.pagination.getTableListData();
          // });
          this.addMenu()
          // }
          // this.action = "show";
        } else {
          return false
        }
      })
    },
    addMenu() {
      var url = ''
      this.isSaveLoading = true
      var inventedIdEmpty = this.formData.inventedId
      this.formData.inventedId = ''

      if (this.action === 'add') {
        url = '/api-m/menus/add'
      } else {
        url = '/api-m/menus/upadte'
      }
      this.formData.isShow = this.managerIsShow ? 0 : 1
      this.axios({
        method: 'post',
        url: url,
        data: this.formData,
      })
        .then(
          (response) => {
            this.isSaveLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              this.$nextTick(() => {
                this.getDept()
                this.action = 'show'
                this.$refs.tree.setCurrentKey(this.formData.id)
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
            this.formData.inventedId = inventedIdEmpty
          },
          (response) => {
            this.isSaveLoading = false
            this.formData.inventedId = inventedIdEmpty
          }
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    cancelSave() {
      this.action = 'show'
      // this.$refs['formData'].resetFields();
    },
    saveSetting() {
      // this.multipleSelection
      this.$message({
        message: '保存成功',
        type: 'success',
      })
    },
    getTableList(data) {
      //---造数据---begin
      this.tableList = data.map((v, i) => {
        if (i === 1) {
          v.checked = true
        }
        return v
      })
      //---造数据---end
      this.$nextTick(() => {
        this.tableList.map((v) => {
          if (v.checked) {
            this.$refs.multipleTable.toggleRowSelection(v)
          }
        })
      })

      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    toShowIcon() {
      if (this.action !== 'show') {
        this.isShowIcon = true
      } else {
        this.isShowIcon = false
      }
    },
  },
  watch: {
    action: {
      handler(val) {
        if (val == 'show') {
          this.showTitle = '菜单详情'
        } else if (val == 'add') {
          this.showTitle = '添加菜单'
        } else {
          this.showTitle = '编辑菜单'
        }
        this.showFrom = false
        this.$nextTick(function () {
          this.showFrom = true
        })
      },
      immediate: true,
    },
  },
}
</script>

<style scoped lang="less">
.custom-tree-node {
  font-size: 14px;
}
.mainContainer {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 24px;
  bottom: 0px;
  background: #fff;
  overflow-y: auto;
  .titleBox {
    .title {
      color: #333;
      font: bold 18px SourceHanSansCN-Medium;
      line-height: 31px;
    }
  }
  .divider {
    margin-top: 15px;
  }
  .departmentMenu {
    width: 30%;
    height: 100%;
    overflow: auto;
    padding: 25px;
    // min-width: 335px;
    background: #e7ecf3;
  }
  .departmentModify {
    width: 70%;
    padding: 25px;
    // position: absolute;
    // top: 0;
    // right: 0;
    // left: 30%;
    .el-form-item {
      // display: inline-block;
      float: left;
      width: 45%;
      height: 45px;
      .input {
        width: 90%;
        height: 20px;
        font: 14px SourceHanSansCN-Medium;
      }
    }
  }
  .emptyBox {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 800px;
    height: 600px;
    .empty {
      color: #999;
      margin: auto;
    }
  }
}

.iconList {
  height: 250px;
  width: 100%;
  overflow: auto;
  border: 1px solid #eee;
  border-radius: 5px;
  position: absolute;
  left: 0;
  top: 36px;
  background: #fff;
  z-index: 1000;
}

.form /deep/ .el-form-item__content {
  // overflow: hidden;
  .menuName {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

form /deep/ .urlName .el-form-item__content {
  div {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.tree
  /deep/
  .el-tree
  /deep/
  .is-expanded
  > .el-tree-node__content
  .custom-tree-node
  span {
  width: 150px;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
